package com.akk.gulimall.product.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.akk.common.utils.PageUtils;
import com.akk.common.utils.Query;

import com.akk.gulimall.product.dao.CategoryDao;
import com.akk.gulimall.product.entity.CategoryEntity;
import com.akk.gulimall.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
//    @Autowired
//    CategoryDao dao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //1.查出所有分類
        List<CategoryEntity> entities = baseMapper.selectList(null);
        //2.組裝成父子的樹型結構
        //a. 找到所有一級分類
//        List<CategoryEntity> level1menu = entities.stream().filter(categoryEntity ->
//            categoryEntity.getParentCid() == 0
//        ).collect(Collectors.toList());
//        List<CategoryEntity> level1menu = entities.stream().filter((categoryEntity) -> {
//            return categoryEntity.getParentCid() == 0;
//        }).collect(Collectors.toList());  基礎寫法
        List<CategoryEntity> level1menu = entities.stream().filter(categoryEntity ->
                categoryEntity.getParentCid() == 0
        ).map((menu)->{
            menu.setChildren(getChildrens(menu,entities));
            return menu;
        }).sorted((menu1,memu2)->{
            return menu1.getSort() - memu2.getSort();
        }).collect(Collectors.toList());

        return level1menu;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO 1.檢查當前刪除的菜單，是否被別的地方引用
        //邏輯刪除
        baseMapper.deleteBatchIds(asList);
    }

    //遞歸查找一級菜單的下屬二級菜單
    private List<CategoryEntity> getChildrens(CategoryEntity root,List<CategoryEntity> all){
        List<CategoryEntity> childern =all.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid() == root.getCatId();
        }).map(categoryEntity -> {
            //1.找到子菜單
            categoryEntity.setChildren(getChildrens(categoryEntity,all));
            return categoryEntity;
        }).sorted((menu1,menu2) -> {
            //2.菜單的排序
            return (null==menu1.getSort()?0:menu1.getSort()) - (null==menu2.getSort()?0:menu2.getSort());
        }).collect(Collectors.toList());


        return childern;
    }
}